package cn.tedu.personal_patient.information.controller;

import cn.tedu.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.common.web.JsonResult;
import cn.tedu.personal_patient.information.pojo.entity.Patient;
import cn.tedu.personal_patient.information.pojo.param.PatientAddNewParam;
import cn.tedu.personal_patient.information.pojo.param.PatientUpdateParam;
import cn.tedu.personal_patient.information.pojo.vo.OutPatient;
import cn.tedu.personal_patient.information.pojo.vo.PatientListVO;
import cn.tedu.personal_patient.information.services.IPatientAddressService;
import cn.tedu.personal_patient.information.services.IPatientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/patients/")
@Validated
@Api(tags = "1. 就诊人管理")
public class PatientController {

    @Autowired
    private IPatientService patientService;

    @Autowired
    private IPatientAddressService patientAddressService;

    @ApiOperation("根据用户ID查询就诊人列表")
    @GetMapping("")
    public JsonResult listByUserId(@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal){
        List<PatientListVO> list = patientService.listByUserId(currentPrincipal);
        return JsonResult.ok(list);
    }

    @ApiOperation("新增就诊人")
    @PostMapping("insert")
    public JsonResult insert(@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal,@Valid PatientAddNewParam patientAddNewParam){
        patientService.insert(currentPrincipal,patientAddNewParam);
        return JsonResult.ok();
    }

    @ApiOperation("更新就诊人信息")
    @PostMapping("update/{id}")
    public JsonResult update(@PathVariable Long id,@Valid PatientUpdateParam patientUpdateParam){
        patientService.update(id, patientUpdateParam);
        return JsonResult.ok();
    }

    @ApiOperation("删除就诊人信息")
    @PostMapping("delete/{id}")
    public JsonResult deleteByPatientId(@PathVariable Long id){
        patientAddressService.deleteByPatientId(id);
        patientService.delete(id);
        return JsonResult.ok();
    }

    @RequestMapping(value = "getExcel",method = RequestMethod.GET)
    @ResponseBody
    public void getExcel(HttpServletResponse response, @AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal) throws IOException {

        // 初始化工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("就诊人信息");

        //设置单元格居中，边框为黑色，边框粗细为1
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);

        //首行合并从A1到E1
        CellRangeAddress mer = new CellRangeAddress(0,0,0,8);
        sheet.addMergedRegion(mer);

        //创建首行表头--合并单元格并居中
        XSSFRow row0 = sheet.createRow(0);
        Cell cell = row0.createCell(0);
        cell.setCellValue("就诊人信息表");

        //设置表头行
        cell.setCellStyle(cellStyle);
        // 创建标题行
        Row header = sheet.createRow(1);
        sheet.setColumnWidth(1,10*256);
        sheet.setColumnWidth(2,10*256);
        sheet.setColumnWidth(3,30*256);
        sheet.setColumnWidth(4,20*256);
        sheet.setColumnWidth(5,20*256);
        sheet.setColumnWidth(6,30*256);
        sheet.setColumnWidth(7,20*256);
        sheet.setColumnWidth(8,50*256);
        Cell cell0 = header.createCell(0);
        Cell cell1 = header.createCell(1);
        Cell cell2 =header.createCell(2);
        Cell cell3 =header.createCell(3);
        Cell cell4 =header.createCell(4);
        Cell cell5 =header.createCell(5);
        Cell cell6 =header.createCell(6);
        Cell cell7 =header.createCell(7);
        Cell cell8 =header.createCell(8);
        cell0.setCellValue("编号");
        cell1.setCellValue("姓名");
        cell2.setCellValue("性别");
        cell3.setCellValue("身份证");
        cell4.setCellValue("出生年月");
        cell5.setCellValue("联系方式");
        cell6.setCellValue("基础病");
        cell7.setCellValue("紧急联系人");
        cell8.setCellValue("地址");
        //设置标题行
        cell0.setCellStyle(cellStyle);
        cell1.setCellStyle(cellStyle);
        cell2.setCellStyle(cellStyle);
        cell3.setCellStyle(cellStyle);
        cell4.setCellStyle(cellStyle);
        cell5.setCellStyle(cellStyle);
        cell6.setCellStyle(cellStyle);
        cell7.setCellStyle(cellStyle);
        cell8.setCellStyle(cellStyle);

        // 插入数据
        List<OutPatient> list = getOutPatientList(currentPrincipal);
        int rowindex=2;
        for (int i = 0; i< list.size(); i++) {
            XSSFRow row2= sheet.createRow(rowindex++);
            OutPatient op = list.get(i);
            //创建单元格并填充数据,  单元格下标从0开始可以直接操作
            Cell con0 =  row2.createCell(0);
            con0.setCellValue(op.getId());
            Cell con1 = row2.createCell(1);
            con1.setCellValue(op.getName());
            String flag = "男";
            if(op.getGender()==0)
                flag = "女";
            Cell con2 =row2.createCell(2);
            con2.setCellValue(flag);
            Cell con3 = row2.createCell(3);
            con3.setCellValue(op.getNumber());
            Cell con4 = row2.createCell(4);
            con4.setCellValue(op.getBirth());
            Cell con5 = row2.createCell(5);
            con5.setCellValue(op.getPhone());
            Cell con6 = row2.createCell(6);
            con6.setCellValue(op.getBackgroundDisease());
            Cell con7 = row2.createCell(7);
            con7.setCellValue(op.getEmergencyContactPhone());
            Cell con8 = row2.createCell(8);
            con8.setCellValue(op.getAddress());

            con0.setCellStyle(cellStyle);
            con1.setCellStyle(cellStyle);
            con2.setCellStyle(cellStyle);
            con3.setCellStyle(cellStyle);
            con4.setCellStyle(cellStyle);
            con5.setCellStyle(cellStyle);
            con6.setCellStyle(cellStyle);
            con7.setCellStyle(cellStyle);
            con8.setCellStyle(cellStyle);
        }
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=就诊人信息.xlsx");
        // 将工作簿写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }


    public List<OutPatient> getOutPatientList(@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal) {
//        List<OutPatient> list = new ArrayList<>();
//        list.add(new OutPatient(1,"张三晓", 0,"120224199911121112","15810061815"));
//        list.add(new OutPatient(2,"李阿四", 0,"120224199911121112","15810151826"));
//        list.add(new OutPatient(3,"张小妹", 1,"120224199911121112","15710061325"));
        List<OutPatient> list = patientService.listUserId(currentPrincipal);
        return list;
    }


    @GetMapping(value = "downExcel")
    public void  downExcel(HttpServletResponse response,@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal) throws IOException {
        //创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建一个sheet
        XSSFSheet sheet = workbook.createSheet("就诊人信息");

        //首行合并从A1到E1
        CellRangeAddress mer = new CellRangeAddress(0,0,0,4);
        sheet.addMergedRegion(mer);

        //创建首行表头--合并单元格并居中
        XSSFRow row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("就诊人信息表");


        //设置单元格居中，边框为黑色，边框粗细为1
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);


        //设置标题行
        XSSFRow row1 = sheet.createRow(1);
        Cell cell0 = row1.createCell(0);
        cell0.setCellValue("编  号");
        Cell cell1 = row1.createCell(1);
        cell1.setCellValue("姓  名");
        Cell cell2 = row1.createCell(2);
        cell2.setCellValue("性  别");
        Cell cell3 = row1.createCell(3);
        cell3.setCellValue("身份证");
        Cell cell4 = row1.createCell(4);
        cell4.setCellValue("出生年月");
        Cell cell5 = row1.createCell(5);
        cell5.setCellValue("联系方式");
        Cell cell6 = row1.createCell(6);
        cell6.setCellValue("基础病");
        Cell cell7 = row1.createCell(7);
        cell7.setCellValue("紧急联系人");
        Cell cell8 = row1.createCell(8);
        cell8.setCellValue("地址");

        cell.setCellStyle(cellStyle);
        cell0.setCellStyle(cellStyle);
        cell1.setCellStyle(cellStyle);
        cell2.setCellStyle(cellStyle);
        cell3.setCellStyle(cellStyle);
        cell4.setCellStyle(cellStyle);
        cell5.setCellStyle(cellStyle);
        cell6.setCellStyle(cellStyle);
        cell7.setCellStyle(cellStyle);
        cell8.setCellStyle(cellStyle);

        //数据填充
        List<OutPatient> list = getOutPatientList(currentPrincipal);
        int rowindex=2;
        //将获取的数据填充到第一行
        for (int i=0;i<list.size();i++){
            XSSFRow row2= sheet.createRow(rowindex++);
            OutPatient op = list.get(i);
            //创建单元格并填充数据,  单元格下标从0开始可以直接操作
            Cell con0 =  row2.createCell(0);
            con0.setCellValue(op.getId());
            Cell con1 = row2.createCell(1);
            con1.setCellValue(op.getName());
            String flag = "男";
            if(op.getGender()==0)
                flag = "女";
            Cell con2 =row2.createCell(2);
            con2.setCellValue(flag);
            Cell con3 = row2.createCell(3);
            con3.setCellValue(op.getNumber());
            Cell con4 = row2.createCell(4);
            con4.setCellValue(op.getBirth());
            Cell con5 = row2.createCell(5);
            con5.setCellValue(op.getPhone());
            Cell con6 = row2.createCell(6);
            con6.setCellValue(op.getBackgroundDisease());
            Cell con7 = row2.createCell(7);
            con7.setCellValue(op.getEmergencyContactPhone());
            Cell con8 = row2.createCell(8);
            con8.setCellValue(op.getAddress());

            con0.setCellStyle(cellStyle);
            con1.setCellStyle(cellStyle);
            con2.setCellStyle(cellStyle);
            con3.setCellStyle(cellStyle);
            con4.setCellStyle(cellStyle);
            con5.setCellStyle(cellStyle);
            con6.setCellStyle(cellStyle);
            con7.setCellStyle(cellStyle);
            con8.setCellStyle(cellStyle);

        }
        //获取文件名
        String fileName="就诊人信息.xlsx";
        //文件名编码格式
        fileName = URLEncoder.encode(fileName, "UTF-8");
        //设置请求头，这里生成完成要下载
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download");
        //获取输出流
        OutputStream outputStream=response.getOutputStream();
        //下载
        workbook.write(outputStream);
        //关闭资源
        outputStream.close();
        workbook.close();
    }
}

//@Data
//@NoArgsConstructor
//@AllArgsConstructor
//class OutPatient  implements Serializable {
//
//    private Integer id;
//    private String name;
//    private int sex;
//    private String card;
//    private String tel;
//
//}

